#!/bin/bash
# Called when analysis is done

# check if we have gnuplot
gnuplot_path=`which gnuplot`
if [ "$gnuplot_path" = "" ]; then
	echo "You don't have gnuplot installed!"
	echo "Please install for this function.!"
	echo "You may continue here, but without plots for Reduced CHISQ and variable shifts."
	read -p "To continue please hit enter, to abort, please hit Ctrl-c."
else
	echo "gnuplot found."
fi

# Produce plot of CHISQ evolution
echo 'set xtics rotate by -15' > temp.plt
echo 'set xrange [*:*]' >> temp.plt
echo 'set logscale y' >> temp.plt
echo 'set xlabel "Rietveld cycle"' >> temp.plt
echo 'set ylabel "Reduced CHISQ"' >> temp.plt
echo 'set y2label "Number of variables"' >> temp.plt
echo 'set yrange [*:100]' >> temp.plt
echo 'set y2range [0:*]' >> temp.plt
echo 'set y2tics border' >> temp.plt
echo 'set ytics nomirror' >> temp.plt
echo 'set key outside below' >> temp.plt
echo 'set output "Reduced.eps"' >> temp.plt
echo 'set terminal postscript eps enhanced color 24' >> temp.plt
echo 'plot \' >> temp.plt
echo '   "< grep Reduced `cat GSAS_EXP`.LST" using 4  title "Reduced CHISQ",\' >> temp.plt
echo '   "< grep Reduced `cat GSAS_EXP`.LST" using 6  axes x1y2 title "Number of variables"' >> temp.plt
gnuplot temp.plt

# generate plot with shift evolution
echo 'set xtics rotate by -15' > temp.plt
echo 'set xrange [*:*]' >> temp.plt
echo 'set logscale y' >> temp.plt
echo 'set xlabel "Rietveld cycle"' >> temp.plt
echo 'set ylabel "Final variable sum((shift/esd)**2)"' >> temp.plt
echo 'set y2label "CPU time/cycle [s]"' >> temp.plt
echo 'set yrange [0.01:*]' >> temp.plt
echo 'set y2range [0:*]' >> temp.plt
echo 'set y2tics border' >> temp.plt
echo 'set key outside below' >> temp.plt
echo 'set ytics nomirror' >> temp.plt
echo 'set output "Shift.eps"' >> temp.plt
echo 'set terminal postscript eps enhanced color 24' >> temp.plt
echo 'plot \' >> temp.plt
# Insert a space after cycle with sed to make sure "cycle" is in column 6 - otherwise at cycles>1000 it becomes 1...
echo '   "< grep Final `cat GSAS_EXP`.LST | sed \"s/cycle/cycle /g\" " using 7  with lines title "Shift",\' >> temp.plt
echo '   "< grep Final `cat GSAS_EXP`.LST | sed \"s/cycle/cycle /g\" " using 9  axes x1y2 title "CPU time"' >> temp.plt
gnuplot temp.plt

echo "\section{Reduced $\chi^2$ and variable shifts}" >> `cat GSAS_EXP`.tex
echo "In this graph, the reduced $\chi^2$ should get gradually smaller during the refinement." >> `cat GSAS_EXP`.tex
echo "\newline" >> `cat GSAS_EXP`.tex
echo "\includegraphics[width=150mm]{Reduced.eps}" >> `cat GSAS_EXP`.tex
echo "\newline" >> `cat GSAS_EXP`.tex
echo "In this graph, the shift should monotonically decrease to values $<0.1$ for each step." >> `cat GSAS_EXP`.tex
echo "If a value substantially greater than 1 is achieved for a given step, the fit was not" >> `cat GSAS_EXP`.tex
echo "converged and more refinement cycles are required (parameter of the gsas\_refine command)." >> `cat GSAS_EXP`.tex
echo "If a sawtooth shaped pattern is observed, oscillations occured and parameters were likely too" >> `cat GSAS_EXP`.tex
echo "highly correlated. If this occurs, check the correlation matrix for the parameters you" >> `cat GSAS_EXP`.tex
echo "turned on during that step and turn off variation of parameters they are correlated with." >> `cat GSAS_EXP`.tex
echo "\newline" >> `cat GSAS_EXP`.tex
echo "\includegraphics[width=150mm]{Shift.eps}" >> `cat GSAS_EXP`.tex
echo "\newline" >> `cat GSAS_EXP`.tex

# Check of parameters that are zero within error bars and output the parameters with their values
echo "\section{Parameters}" >> `cat GSAS_EXP`.tex
awk -v FIELDWIDTHS="13 16 16" '{if (NR>1 && $2!=0) {if ($3*$3/$2/$2>1) print $1};}' `cat GSAS_EXP`.PVE > out.txt
if [ -s out.txt ]; then
  echo "The following parameters have values that are zero within their error bars. " >> `cat GSAS_EXP`.tex
  echo "Unless they are atomic positions, you should consider removing these " >> `cat GSAS_EXP`.tex
  echo "parameters from the refinement." >> `cat GSAS_EXP`.tex
  echo "\begin{verbatim}" >> `cat GSAS_EXP`.tex
  cat out.txt >> `cat GSAS_EXP`.tex
  echo "\end{verbatim}" >> `cat GSAS_EXP`.tex
else
  echo "No parameters have values that are zero within their error bars. " >> `cat GSAS_EXP`.tex
fi

# Check of thermal motion parameters that are smaller than zero
grep UISO `cat GSAS_EXP`.PVE | awk -v FIELDWIDTHS="13 16 16" '{if ($2<0) print $1}'  > out.txt
if [ -s out.txt ]; then
  echo "The following isotropic thermal motion parameters have un-physical negative values:" >> `cat GSAS_EXP`.tex
  echo "\begin{verbatim}" >> `cat GSAS_EXP`.tex
  cat out.txt >> `cat GSAS_EXP`.tex
  echo "\end{verbatim}" >> `cat GSAS_EXP`.tex
else
  echo "No isotropic thermal motion parameters have un-physical negative values." >> `cat GSAS_EXP`.tex
fi

# Check of site occupation parameters that are smaller than zero
grep FRAC `cat GSAS_EXP`.PVE | awk -v FIELDWIDTHS="13 16 16" '{if ($2<0) print $1}'  > out.txt
if [ -s out.txt ]; then
  echo "The following site occupation parameters have un-physical negative values:" >> `cat GSAS_EXP`.tex
  echo "\begin{verbatim}" >> `cat GSAS_EXP`.tex
  cat out.txt >> `cat GSAS_EXP`.tex
  echo "\end{verbatim}" >> `cat GSAS_EXP`.tex
else
  echo "No site occupation parameters have un-physical negative values." >> `cat GSAS_EXP`.tex
fi

# Check of site occupation parameters that are greater than one
grep FRAC `cat GSAS_EXP`.PVE | awk -v FIELDWIDTHS="13 16 16" '{if ($2>1) print $1}'  > out.txt
if [ -s out.txt ]; then
  echo "The following site occupation parameters have un-physical values greater than 1:" >> `cat GSAS_EXP`.tex
  echo "\begin{verbatim}" >> `cat GSAS_EXP`.tex
  cat out.txt >> `cat GSAS_EXP`.tex
  echo "\end{verbatim}" >> `cat GSAS_EXP`.tex
else
  echo "No site occupation parameters have un-physical values greater than 1." >> `cat GSAS_EXP`.tex
fi

echo "The refined parameters and their values and esds are:" >> `cat GSAS_EXP`.tex
echo "\begin{verbatim}" >> `cat GSAS_EXP`.tex
cat `cat GSAS_EXP`.PVE >> `cat GSAS_EXP`.tex
echo "\end{verbatim}" >> `cat GSAS_EXP`.tex
echo "\end{document}" >> `cat GSAS_EXP`.tex
echo "Generating DVI file..."

# Produce PDF file with information
latex `cat GSAS_EXP`.tex
if [ "$OS" = "Windows_NT" ]; then
	echo "I think I run on a Windows box..."
	dvips `cat GSAS_EXP`
	ps2pdf `cat GSAS_EXP`.ps
else
	echo "I think I run on a Unix box..."
	echo "Generating PDF file..."
	dvipdf `cat GSAS_EXP`.dvi
	#acroread `cat GSAS_EXP`.pdf
fi

# Was a phase fraction refined?
grep "PHFR" `cat GSAS_EXP`.PVE > temp.txt
if [ $? -eq 0 ]; then
  # phase scale was refined, let's add the weight fraction (need to do error bars on another day...
  for ((phase=1;phase<=`gsas_get_number_of_phases`;phase++)); do
    wtfrac=`gsas_get_current_wtfrac $phase`
    wtfrac_esd=`gsas_get_current_wtfrac_esd $phase`
    echo "Outputting phase fraction of phase $phase ($wtfrac +/- $wtfrac_esd) to PVE file..."
    echo "dummy" | awk -v phase=$phase -v val=$wtfrac -v esd=$wtfrac_esd '{printf("  \042%d   WTFR\042    %8.6e    %8.6e\n",phase,val,esd)}'  >> `cat GSAS_EXP`.PVE
  done
fi

# clean up
rm out.txt
rm temp.txt
rm temp2.txt
rm maxtof.txt
rm maxtof2.txt
rm shift.txt
rm chisq.txt
rm *.EPS
rm `cat GSAS_EXP`.dvi
rm `cat GSAS_EXP`.log
rm `cat GSAS_EXP`.aux
rm `cat GSAS_EXP`.tex
rm `cat GSAS_EXP`.CMT
rm `cat GSAS_EXP`.O??
rm `cat GSAS_EXP`.P[^VE]*
rm `cat GSAS_EXP`.R??
rm gsas_print.txt
rm gsas_step.txt
rm hist.txt
rm nhist.txt
rm powpref
rm powplot
rm genles
rm expedt
rm GSAS_EXP
rm flag.txt
rm Reduced.eps
rm Shift.eps
rm temp.plt

# compute the total run time
START=`cat gsas_start.txt`
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Total run time since gsas_initialize: $DIFF seconds."

